/*
 * @Author       : NaN 353362604@qq.com
 * @Date         : 2023-01-30 15:32:02
 * @LastEditTime : 2023-08-27 11:15:32
 * @LastEditors  : NaN 353362604@qq.com
 * @FilePath     : \AdminStration\src\Pages\Front\Assets\Command\CommandOne.jsx
 * @Description  :
 */

import './_Command.scss'

import { Button, Tree, message } from 'antd'
import { Http } from '../../../../Common/Api'
import { useEffect, useRef, useState } from 'react'

import { useEventEmitter, useRequest } from 'ahooks'
import { useLatest } from '@ant-design/pro-components'
import { PhoneFilled } from '@ant-design/icons'
import { TreeToLevel } from '../../../../Common/Configure/Common'
import { initializationPlaneMap } from '../Common/PlaneMap'

import { project } from '../../../../Common/Data'
const { imageUrl } = project[window.location.hostname]
const { mars3d, Cesium } = window
const ProjectColor = ['#44A0FF', '#20D660']

const polylineDataList = [
    'fb19983f-f648-4f0c-b6e2-5dfb2f3f3b2c',
    '79b8e61f-d4a7-40ab-9256-2d3205b50e5b',
    '1628a177-825c-428d-afa7-e3bd7b0a481d',
    'db6baf0b-ebed-4cb4-8638-37e48853ec2f',
]

// 地图
const Map = ({ MapEvent, UserList, MapOptions, MapSetUp }) => {
    // const Navigate = useNavigate()
    const [UserData, setUserData] = useState()
    const Mars3dBox = useRef()
    const [Map, setMap] = useState()
    const [Gra, setGra] = useState()

    MapEvent.useSubscription(val => {
        // if (Gra.getGraphicById(val)) Map.flyToGraphic(Gra.getGraphicById(val), { radius: 500 })
    })

    const { runAsync: getHelmetAllPositions } = useRequest(Http, {
        manual: true,
        pollingInterval: 30000,
        pollingWhenHidden: false,
        onSuccess: res => PersonnelInit(res),
    })

    const { runAsync: getProjectList } = useRequest(Http, {
        manual: true,
        onSuccess: ({ list }) => {
            getHelmetAllPositions({ url: 'getHelmetAllPositions' })
        },
    })

    useEffect(() => {
        if (UserList && UserList?.length !== 0) {
            const { map, gra } = initializationPlaneMap(Mars3dBox, MapOptions, MapSetUp)
            map.centerAt({ lat: 43.682958, lng: 129.154755, alt: 1556122.8, heading: 355, pitch: -72.3 })
            setMap(map)
            setGra(gra)
            let data = {}
            TreeToLevel(UserList)
                .filter(v => v.helmetType !== 0)
                .forEach(({ deviceSerial, personName }) => {
                    data = { ...data, [deviceSerial]: `${personName}` }
                })
            setUserData(data)
            getProjectList({ url: 'getProjectList' })
        }
    }, [MapOptions, MapSetUp, UserList, getProjectList])

    // 初始化状态
    const PersonnelInit = res => {
        Object.keys(UserData).forEach(item => {
            if (UserData[item] && res[item]) {
                if (Gra.getGraphicById(item)) {
                    if (JSON.stringify(res[item]) !== '{}') {
                        Gra.getGraphicById(item).show = true
                        Gra.getGraphicById(item).position = [res[item].lon, res[item].lat, 0]
                    } else Gra.getGraphicById(item).show = false
                } else {
                    const graphic = new mars3d.graphic.BillboardEntity({
                        id: item,
                        position: [res[item].lon, res[item].lat, 0],
                        style: {
                            clampToGround: true,
                            image: `${imageUrl}${
                                UserData[item].indexOf('执法记录仪') !== -1 ? 'command002.png' : 'command001.png'
                            }`,
                            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                            label: {
                                text: UserData[item],
                                color: 'white',
                                pixelOffsetY: -80,
                                outline: true,
                                font_size: 22,
                                font_weight: 'bold',
                                outlineColor: 'rgba(0, 0, 0, 0.30)',
                            },
                        },
                    })
                    Gra.addGraphic(graphic)
                }
            }
        })
    }
    return <div className="Map" ref={Mars3dBox} />
}

const CommandBox = ({ data, MapEvent, CMT_ADMIN }) => {
    const [SelectList, setSelectList] = useState([])
    // 初始化三方sdk
    const [CMTSDK, setCMTSDK] = useState()
    const SDKLatest = useLatest(CMTSDK)
    // 初始化安全帽
    const [UserList, setUserList] = useState({})

    // 安全帽socket事件
    useEffect(() => {
        const InItCmtClientService = () => {
            const { user, password, host, serverPort } = CMT_ADMIN
            SDKLatest.current = new window.CmtWsClientHelper()
            window.onopen = () => SDKLatest.current.registerSip(user, password, host, serverPort)
            window.setConfig = () =>
                SDKLatest.current.setServiceConfig(
                    'videoPlayUrl',
                    `http://${host}:1080/vdis/videoPlayer?user=${user}&passwd=${password}`,
                )
            window.location = 'CmtClientService://'
            SDKLatest.current.addCmtEventHandler(new window.CallbackHandler())
            SDKLatest.current.init()
            setCMTSDK(SDKLatest.current)
        }
        // 卸载安全帽
        const UnInItCmtClientService = () => {
            SDKLatest.current.closeService()
            SDKLatest.current.WSClose()
            window.onopen = () => null
            window.setConfig = () => null
        }
        InItCmtClientService()
        return () => {
            UnInItCmtClientService()
        }
    }, [CMT_ADMIN, SDKLatest])

    useEffect(() => {
        window.onEventFiredEvent = e => {
            const { event, code } = e
            switch (event) {
                case 'onOpen':
                    window.onopen()
                    break
                case 'onEventRegistered':
                    if (Number(code) === 200) {
                        message.success('指挥中心登录成功!')
                        window.setConfig()
                    } else {
                        message.error('指挥中心登录失败!')
                    }
                    break
                case 'onClose':
                    CMTSDK.WSClose()
                    CMTSDK.init()
                    message.error('指挥中心重新连接中...')
                    break
                case 'onEventUserStatusUpdate':
                    setUserList(Update => {
                        Update = { ...Update, [e.sipNum]: e.status }
                        MapEvent.emit(Update)
                        return Update
                    })
                    break
                case 'onEventConnected':
                    e.type === 'audio' && console.log('语音事件', e)
                    e.type === 'video' && console.log('视频事件', e)
                    break
                default:
                    // console.log('通知事件', e)
                    break
            }
            window.onCmdResultEvent = e => {
                const { cmdName } = e
                switch (cmdName) {
                    case 'registerSip':
                        message.loading('指挥中心初始化中')
                        break
                    default:
                        console.log('返回事件', e)
                        break
                }
            }
        }

        return () => {
            window.onEventFiredEvent = () => {}
            window.onCmdResultEvent = () => {}
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [CMTSDK, data])

    //
    return (
        <div>
            <Tree
                checkable
                fieldNames={{ title: 'personName', key: 'uuid' }}
                onCheck={e => setSelectList(e)}
                treeData={data}
                titleRender={e => {
                    const { deviceSerial, personName } = e
                    return (
                        <div
                            className="treeBox"
                            onClick={() => {
                                if (UserList[deviceSerial] && UserList[deviceSerial] !== '2')
                                    MapEvent.emit(deviceSerial)
                            }}
                        >
                            <div className="personName">
                                {deviceSerial} - {personName}
                            </div>
                            {deviceSerial && (
                                <div className="status">
                                    {(() => {
                                        switch (UserList[deviceSerial]) {
                                            case '1':
                                                return <div>在线</div>
                                            case '2':
                                                return <div style={{ color: '#858585' }}>离线</div>
                                            case '3':
                                                return <div>通话中</div>
                                            default:
                                                return <div>初始化...</div>
                                        }
                                    })()}
                                </div>
                            )}
                        </div>
                    )
                }}
            />
            <div>
                <Button
                    block
                    size="large"
                    type="primary"
                    icon={<PhoneFilled />}
                    disabled={SelectList.length === 0 ? true : false}
                    onClick={() => {
                        SelectList.forEach(item => {
                            console.log(item)
                            let { deviceSerial } = TreeToLevel(data).find(v => v.uuid === item)
                            CMTSDK.makeVideoCall(deviceSerial, 0, 0)
                        })
                    }}
                >
                    指挥对讲
                </Button>
            </div>
        </div>
    )
}

export const CommandOne = ({ CMT_ADMIN, MapOptions, MapSetUp }) => {
    const [UserList, setUserList] = useState()
    const { runAsync: getSecurityStatHelmetTree } = useRequest(Http, {
        manual: true,
        onSuccess: res => setUserList(res),
    })
    useEffect(() => {
        getSecurityStatHelmetTree({ url: 'getSecurityStatHelmetTree' })
    }, [getSecurityStatHelmetTree])
    const MapEvent = useEventEmitter()

    return (
        <div className="CommandOne">
            <div className="Left">
                <CommandBox data={UserList} MapEvent={MapEvent} CMT_ADMIN={CMT_ADMIN} />
            </div>
            <div className="Right">
                <Map MapEvent={MapEvent} UserList={UserList} MapOptions={MapOptions} MapSetUp={MapSetUp} />
            </div>
        </div>
    )
}
